package com.ccp.dev.workflow.listener;

import com.ccp.dev.core.basic.engine.GroovyScriptEngine;
import com.ccp.dev.core.util.AppUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.workflow.bpmconst.BpmConst;
import com.ccp.dev.workflow.model.BpmNodeScript;
import com.ccp.dev.workflow.service.BpmNodeScriptService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * ClassDescribe:
 * 子流程结束事件监听器
 * @author :wangcheng
 * Date: 2019-05-13
 */
@Component
public class SubProcessEndListener implements ExecutionListener {
    @Override
    public void notify(DelegateExecution execution) {
        Integer nrOfInstances=(Integer)execution.getVariable("nrOfInstances");
        Integer nrOfCompletedInstances=(Integer)execution.getVariable("nrOfCompletedInstances");
        //子流程第一次执行
        if(nrOfInstances==null || (nrOfCompletedInstances!=null &&  nrOfInstances.equals(nrOfCompletedInstances))){
            String actDefId=execution.getProcessDefinitionId();
            String nodeId=execution.getCurrentActivityId();
            exeEventScript(execution, BpmConst.END_SCRIPT,actDefId,nodeId);
        }
    }

    private void exeEventScript(DelegateExecution execution,int scriptType,String actDefId,String nodeId ){
        BpmNodeScriptService bpmNodeScriptService=(BpmNodeScriptService) AppUtil.getBean("bpmNodeScriptService");
        BpmNodeScript model=bpmNodeScriptService.getScriptByType(nodeId, actDefId, scriptType);
        if (BeanUtils.isEmpty(model)) {
            return;
        }

        String script=model.getScript();
        if(StringUtil.isEmpty(script)){ return;}

        GroovyScriptEngine scriptEngine=(GroovyScriptEngine)AppUtil.getBean("scriptEngine");
        Map<String, Object> vars=execution.getVariables();
        vars.put("execution", execution);
        scriptEngine.execute(script, vars);
    }
}
